package com.mall.order.services;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCloseService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.order.dto.DeleteOrderRequest;
import com.mall.order.dto.DeleteOrderResponse;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.log4j.Log4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Log4j
@Component
@SuppressWarnings("all")
public class OrderCloseServiceImpl implements OrderCloseService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;

    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        try {
            request.requestCheck();
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse, e);
            return cancelOrderResponse;
        }

        String orderId = request.getOrderId();

        try {
            //订单已发货不能取消
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order.getStatus() >= OrderConstants.ORDER_STATUS_SHIPPED) {
                cancelOrderResponse.setCode(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode());
                cancelOrderResponse.setMsg("订单已发货无法取消");
                return cancelOrderResponse;
            }

            //订单未发货前直接取消
            //修改订单状态
            Order newOrder = new Order();
            newOrder.setOrderId(orderId);
            newOrder.setUpdateTime(new Date());
            newOrder.setCloseTime(new Date());
            newOrder.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            orderMapper.updateByPrimaryKeySelective(newOrder);

            //修改库存
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            for (OrderItem orderItem : orderItems) {
                Stock stock = new Stock();
                stock.setItemId(orderItem.getItemId());
                stock.setLockCount(-orderItem.getNum());
                stock.setStockCount(orderItem.getNum().longValue());
                stockMapper.updateStock(stock);
            }


            //修改订单商品的锁定状态
            Example orderItemExample = new Example(OrderItem.class);
            Example.Criteria orderItemCriteria = orderItemExample.createCriteria();
            orderItemCriteria.andEqualTo("orderId", orderId);
            OrderItem orderItem = new OrderItem();
            orderItem.setStatus(2);
            orderItem.setUpdateTime(new Date());
            orderItemMapper.updateByExampleSelective(orderItem, orderItemExample);
        } catch (Exception e) {
            cancelOrderResponse.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
            return cancelOrderResponse;
        }


        //返回
        cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
        cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        return cancelOrderResponse;
    }

    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
        try {
            request.requestCheck();
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse, e);
            return deleteOrderResponse;
        }

        String orderId = request.getOrderId();

        try {
            //删除订单，校验订单的状态，未完成的订单不能删除
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order.getStatus() == OrderConstants.ORDER_STATUS_INIT || order.getStatus() == OrderConstants.ORDER_STATUS_PAYED) {
                deleteOrderResponse.setMsg("订单未完成不能删除,请确认收货或取消订单");
                deleteOrderResponse.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
                //deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
                return deleteOrderResponse;
            }
            //删除订单
            orderMapper.deleteByPrimaryKey(orderId);

            //删除订单商品
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId", orderId);
            orderItemMapper.deleteByExample(example);

            //删除订单地址
        } catch (Exception e) {
            deleteOrderResponse.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            deleteOrderResponse.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
            return deleteOrderResponse;
        }
        deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
        deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        return deleteOrderResponse;
    }

//    @PostMapping("cancelOrder")
//    public ResponseData cancelOrder(@RequestBody Map<String, Long> map) {
//        Long id = map.get("id");
//        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
//        cancelOrderRequest.setOrderId(id.toString());
//        CancelOrderResponse cancelOrderResponse = orderCloseService.cancelOrder(cancelOrderRequest);
//        if (cancelOrderResponse.getCode().equals(OrderRetCode.SUCCESS.getCode()))
//            return new ResponseUtil<String>().setData("成功");
//        return new ResponseUtil().setErrorMsg(Integer.valueOf(cancelOrderResponse.getCode()), cancelOrderResponse.getMsg());
//    }
//
//    @DeleteMapping("order/{id}")
//    public ResponseData deleteOrder(@PathVariable("id") Long orderId) {
//        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
//        deleteOrderRequest.setOrderId(orderId.toString());
//        DeleteOrderResponse deleteOrderResponse = orderCloseService.deleteOrder(deleteOrderRequest);
//        if (deleteOrderResponse.getCode().equals(OrderRetCode.SUCCESS.getCode()))
//            return new ResponseUtil<String>().setData("成功");
//        return new ResponseUtil().setErrorMsg(Integer.valueOf(deleteOrderResponse.getCode()), deleteOrderResponse.getMsg());
//    }
}
